<script setup lang="ts">
import { reactive, onMounted, watch } from 'vue';
import { eventCenter, getCurrentInstance } from '@tarojs/taro';
import dayjs from 'dayjs';
import { Right as AppNutIconRight } from '@nutui/icons-vue-taro';
const props = defineProps<{
  item: FlowPathTemplateApi.AttributeExtendDto;
}>();
const emits = defineEmits<{
  (e: 'onChange', value: string): void;
}>();
//局部
const state = reactive<{
  /**
   * 日期选择
   */
  TimePickerVisible: boolean;
  date: string;
}>({
  TimePickerVisible: false,
  date: '',
});
watch(
  () => props.item.attributeValue,
  () => {
    state.date = props.item.attributeValue || '';
  },
);

//页面-只读-显示-结果
if (props.item.readonlyAble === 1 && props.item.attributeValue) {
  state.date = props.item.attributeValue;
}

//页面-可编辑-默认选项-显示-结果
if (props.item.editAble === 1 && props.item.attributeValue && props.item.attributeDefault) {
  state.date = props.item.attributeValue;
}

const minDate = dayjs().subtract(8, 'year').toDate();
const maxDate = dayjs().add(8, 'year').toDate();
const currentDate = new Date();
const confirm = ({ selectedValue }) => {
  if (selectedValue.length === 3) {
    state.date = selectedValue.join('-');
  } else {
    const date = selectedValue.slice(0, 3).join('-');
    const time = selectedValue.slice(3).join(':');
    state.date = date + ' ' + time;
  }
  emits('onChange', state.date);
  state.TimePickerVisible = false;
};
/**
 * 选择日期
 */
function selectDate() {
  state.TimePickerVisible = !state.TimePickerVisible;
}
onMounted(() => {
  eventCenter.on(getCurrentInstance().router?.onShow as string, () => {
    //清理数据，当成功页面返回的时候，显示初始状态
    state.date = '';
    //页面-可编辑-默认选项-显示-结果
    if (props.item.editAble === 1 && props.item.attributeValue && props.item.attributeDefault) {
      state.date = props.item.attributeValue;
    }
  });
});
</script>
<template>
  <!--3-日期-->
  <!--只读 -->
  <template v-if="item.readonlyAble === 1">
    <nut-cell :title="item.attributeName" :desc="item.attributeValue" />
  </template>
  <!--编辑 -->
  <template v-else>
    <nut-form-item
      :label="item.attributeName"
      :required="item.attributeRequired === 1"
      :label-width="120"
    >
      <view class="approve-edit-select-date" @click="selectDate()">
        <text>{{ state.date || (item.tips ? item.tips : '请选择日期') }}</text>
        <app-nut-icon-right />
      </view>
      <nut-popup position="bottom" v-model:visible="state.TimePickerVisible">
        <nut-date-picker
          :model-value="currentDate"
          :min-date="minDate"
          :max-date="maxDate"
          :type="props.item.attributeDateFormat === 'yyyy-MM-dd' ? 'date' : 'datetime'"
          :is-show-chinese="true"
          @confirm="confirm"
          @cancel="state.TimePickerVisible = false"
        >
        </nut-date-picker>
      </nut-popup>
    </nut-form-item>
  </template>
</template>
<style lang="scss">
.approve-edit-select-date {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>
